#!/usr/bin/env lua

module('afu.response',package.seeall)

local table_insert = table.insert
local table_concat = table.concat
local string_match = string.match
local tirtemplate = require('tirtemplate')

Response={}

function Response:new(env, con)
    local ret={
        _con=con,
        _header={},
        _cookies={},
        _output={},
        _last_func=nil,
        _eof=false
    }
    setmetatable(ret,self)
    self.__index=self
    return ret
end

--[[
设置重定向
]]--
function Response:redirect(url, status)
	self._con:header("Status", status)
	self._con:header("Location", url)
end

function Response:write(content)
    if self._eof==true then
        local error_info = "WARNING: The response has been explicitly finished before."
        return
    end

    table_insert(self._output,content)
end

--[[
设置header，多次设置同名header，视为追加
]]--
function Response:header(name, value) 
	self._header[name] = value
end

function Response:writeln(content)
    if self._eof==true then
        local error_info = "WARNING: The response has been explicitly finished before."
        return
    end

    table_insert(self._output,content)
    table_insert(self._output,"\r\n")
end

function Response:error(info)
    local error_info = "ERROR: " .. info
    self._con:log(error_info)    
    if self._eof==false then
        self:header('Status', 500)
        self:header('Content-Type', 'text/html; charset=utf-8')
        self._con:puts(error_info)
    end
end

function Response:is_finished()
    return self._eof
end

function Response:sendheader( )
    if not self._header['Content-Type'] then
        self:header('Content-Type', 'text/html; charset=utf-8')
    end
    for n, v in pairs(self._header) do
        self._con:header(n, v)
    end
    self._header = {}
end

--template
function Response:tpl(data, filename) 
    local page = tirtemplate.tload(filename)
    local context = data
    -- render template with counter as context

    table_insert(self._output, page(context))    
end

function Response:finish()
    if self._eof==true then
        return
    end

    self._eof = true
    self:sendheader()
    self._con:puts(table_concat(self._output))
    self._output = nil
end
